package com.lyl.yeb.config.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lylbell
 * @date 2022-03-03 14:36
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Value("jwt.tokenHeader")
    private String tokenHeader;

    @Value("jwt.tokenHead")
    private String tokenHead;

    @Resource
    private UserDetailsService userDetailsService;


    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader(tokenHeader);
        // 存在token
        if (header != null && header.startsWith(this.tokenHead)) {
            String token = header.substring(tokenHead.length());
            String username = jwtTokenUtil.getUsernameFromToken(token);
            // 如果token中存在用户名，但并未登录
            if (StringUtils.isBlank(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 登录
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                // 验证token是否有效，重新设置用户对象
                if (jwtTokenUtil.validateToken(token,userDetails)) {
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
